package log

import (
	"fmt"
	"os"
	"svcfwin/config"

	"github.com/sirupsen/logrus"
)

var Log *logrus.Logger = logrus.New()

func InitLog() {
	Log.SetFormatter(&logrus.TextFormatter{ // 设置日志格式
		FullTimestamp: true,
	})
}

func SetLogLevel(loglevel string) {
	switch config.Config.Log.Level { // 根据配置文件中的日志级别设置日志级别
	case "debug":
		Log.SetLevel(logrus.DebugLevel)
	case "info":
		Log.SetLevel(logrus.InfoLevel)
	case "warn":
		Log.SetLevel(logrus.WarnLevel)
	case "error":
		Log.SetLevel(logrus.ErrorLevel)
	case "fatal":
		Log.SetLevel(logrus.FatalLevel)
	case "panic":
		Log.SetLevel(logrus.PanicLevel)
	case "trace":
		Log.SetLevel(logrus.TraceLevel)
	case "*":
		Log.SetLevel(logrus.InfoLevel)
	}
}

func SetLogFile(logfile string) error {
	if config.Config.Log.File == "" { // 如果配置文件中的日志文件不为空，则设置日志文件
		return fmt.Errorf("log file not set")
	}
	file, err := os.OpenFile(logfile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		return fmt.Errorf("failed to open log file: %v", err)
	}
	Log.SetOutput(file)
	return nil
}
